package com.l024.easyandroidlib.http;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.support.retrofit.Retrofit2ConverterFactory;
import com.l024.easyandroidlib.http.config.HttpConfig;
import com.l024.easyandroidlib.http.interceptor.HttpCommonInterceptor;
import com.l024.easyandroidlib.http.ssl.MySSLSocketFactory;
import com.l024.easyandroidlib.http.ssl.TrustAllCerts;
import com.l024.easyandroidlib.http.ssl.TrustAllHostnameVerifier;

import java.net.Proxy;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * @Author: Cat
 * @CreateTime: 2022-07-29  09:39
 * @Description: 网络请求管理类
 * @Version: 1.0
 */
public class HttpManager {
    private static final int DEFAULT_TIME_OUT = 60;//超时时间 5s
    private static final int DEFAULT_READ_TIME_OUT = 60;
    private static HttpManager httpManager;
    private static Retrofit mRetrofit;
    private HttpManager(){}

    public static HttpManager getInstance(){
        if(httpManager==null){
            synchronized (HttpManager.class){
                if(httpManager==null){
                    httpManager = new HttpManager();
                }
            }
        }
        return httpManager;
    }

    public void init(HttpConfig httpConfig){
        if(httpConfig==null){
            throw new RuntimeException("网络请求配置不可为空");
        }else if(TextUtils.isEmpty(httpConfig.baseUrl())){
            throw new RuntimeException("网络请求地址不可为空");
        }
        // 创建 OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置是否代理
        if(!httpConfig.debug()){
            builder.proxy(Proxy.NO_PROXY);
        }
        builder.connectTimeout(httpConfig.getConnectTime(), TimeUnit.SECONDS);//连接超时时间
        builder.readTimeout(httpConfig.getReadTime(),TimeUnit.SECONDS);//读操作超时时间
        builder.writeTimeout(httpConfig.getWriteTime(),TimeUnit.SECONDS);//写超时时间
        //处理ssl
        builder.sslSocketFactory(MySSLSocketFactory.createSSLSocketFactory(), new TrustAllCerts());
        builder.hostnameVerifier(new TrustAllHostnameVerifier());
        HttpCommonInterceptor.Builder interceptorBuilder = new HttpCommonInterceptor.Builder();
        //添加header
        Map<String, String> headers = httpConfig.addHeaders();
        //添加请求头
        if(headers!=null&&headers.size()>0){
            for(Map.Entry<String,String> params:headers.entrySet()){
                interceptorBuilder.addHeaderParams(params.getKey(),params.getValue());
            }
        }
        //添加参数
        Map<String, String> params = httpConfig.addParams();
        if(params!=null&&params.size()>0){
            for(Map.Entry<String,String> param:params.entrySet()){
                interceptorBuilder.addGetParams(param.getKey(),param.getValue());
            }
        }
        //添加拦截器
        builder.addInterceptor(interceptorBuilder.build());
        //添加其他拦截器
        Set<Interceptor> interceptors = httpConfig.addInterceptor();
        if(interceptors!=null&&interceptors.size()>0){
            for(Interceptor interceptor:interceptors){
                builder.addInterceptor(interceptor);
            }
        }
        // Log信息拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i(HttpManager.class.getName(),message);
            }
        });
        //设置日志打印级别
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //将拦截器添加到ok中
        builder.addInterceptor(loggingInterceptor);
        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(Retrofit2ConverterFactory.create())
                .baseUrl(httpConfig.baseUrl())
                .build();
    }

    /**
     * 获取对应的Service
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service){
        return mRetrofit.create(service);
    }

    //设置不同的url
    public <T> T create(String url,Class<T> service){
        return mRetrofit.newBuilder()
                .baseUrl(url)
                .build()
                .create(service);
    }


    public Retrofit getRetrofit() {
        return mRetrofit;
    }
}
